package security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import security.service.impl.LoginUser;
import security.utils.JwtUtil;
import springfox.documentation.spi.service.contexts.SecurityContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter{
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private ObjectMapper mapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            //如果token为空  直接放行
            filterChain.doFilter(request,response);
            return; //防止返回的时候访问后续代码
        }
        //解析token
        Claims claims = JwtUtil.parseJWT("qwe!@#123", token);
        Integer id = (Integer) claims.get("id");
        //从redis中获取该用户
        String json_user = template.opsForValue().get("login:" + id);
        if(json_user==null){
            throw new RuntimeException("用户非法");
        }
        LoginUser loginUser = mapper.readValue(json_user, LoginUser.class);
        //将对象封装为Authentication
        //TODO 后续将权限添加进来
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        //将解析到的数据存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //放行
        filterChain.doFilter(request,response);
    }
}
